<template autoRoute="true">
  <div class="base-info-container">
    <div class="top">
      <div class="form-title">基础字段设置</div>
      <div class="form-content">
        <FormRenderer
          class="form-container"
          labelWidth="120px"
          v-model="formData"
          :schema="formSchema"
        />
        <div class="cover-container">
          <el-upload
            ref="uploadRef"
            class="cover-uploader"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :limit="1"
            :on-change="handleAvatarSuccess"
            accept="image/*"
          >
            <img
              v-if="formData.cover"
              :src="formData.cover"
              class="cover_image"
            />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <el-button>更改封面</el-button>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="form-title flexs">
        <span>自定义字段</span>

        <el-popover
          placement="right"
          :width="250"
          popper-class="field-sort-popover"
          :show-arrow="false"
          trigger="click"
        >
          <template #reference>
            <div class="field-setting">
              <img src="@/assets/pm/fieldSortSetting.svg" />
              <span>字段配置</span>
            </div>
          </template>
          <FormFieldSortPopup
            :fields="getCustomFormSchema"
            @addField="isShowAddFieldDialog = true"
          />
        </el-popover>
      </div>
      <FormRenderer
        class="form-container"
        labelWidth="120px"
        v-model="formData"
        :schema="getCustomFormSchema"
      />
    </div>
    <el-button class="save-btn" type="primary" @click="save">保存</el-button>
  </div>

  <AddFieldDialog
    title="新建"
    v-model="isShowAddFieldDialog"
    @handleSubmit="handleCreateOrEdit"
  />
</template>

<script lang="ts" setup name="基本信息">
  import { computed, onMounted, reactive, ref, useTemplateRef } from "vue";
  import { useRoute } from "vue-router";
  import { projectOverviewAJAX } from "@/api/project";
  import { editBaseInfoAJAX } from "@/api/pm/baseInfo.ts";
  import FormRenderer from "@/components/FormRenderer.vue";
  import FormFieldSortPopup from "@/components/FormFieldSortPopup.vue";
  import type { UploadFile, UploadInstance, UploadProps } from "element-plus";
  import { ElMessage } from "element-plus";
  import { Plus } from "@element-plus/icons-vue";
  import AddFieldDialog from "./AddFieldDialog.vue";
  import { getProjectTypeList, getTest } from "@/api/pm/globalProjectTask.ts";
  import { formatDate } from "@/utils/common.ts";
  import type {
    EditBaseInfoParams,
    FormData,
    FormSchemaItem,
    IOptions,
    ProjectOverviewResponse,
    ProjectTypeItem,
    ProjectTypeListResponse,
  } from "@/interface/pm/baseInfo.ts";
  import { getDetailByTargetType } from "@/api/pm/baseFieldManagement.ts";
  import { getFieldType } from "@/components/CLTable/index.ts";

  const route = useRoute();

  // 响应式数据
  const formData = reactive<FormData>({
    name: "",
    code: "",
    projectTypeId: "",
    plannedDate: [],
    plannedDurationDay: "",
    plannedDurationDayUnit: "天",
    actualDurationDay: "",
    actualDurationDayUnit: "天",
    actualDate: [],
    remark: "",
    cover: "",
  });

  const isShowAddFieldDialog = ref<boolean>(false);
  const projectList = ref<IOptions[]>([]);
  const uploadRef = useTemplateRef<UploadInstance>("uploadRef");

  // 方法
  const getProjectOverview = async (): Promise<void> => {
    const id = route.query.projectId as string;
    try {
      const res: ProjectOverviewResponse = await projectOverviewAJAX(id);
      console.log("getProjectOverview", res);
      formData.name = res.name.zh_CN;
      formData.code = res.code;
      formData.projectTypeId = res.projectTypeId;
      formData.plannedDate = [res.plannedStartTime, res.plannedEndTime];
      formData.actualDate = [res.actualStartTime, res.actualEndTime];
      formData.plannedDurationDay = res.plannedDurationDay;
      formData.actualDurationDay = res.actualDurationDay;
      formData.remark = res.remark;
      formData.cover = res.cover;
      // const fields = await getProjectTemplateDetail(
      //   res.projectTypeId as string,
      // );
      // projectTemplateFields.value = fields.data;
      personalCustomFields.value = res.customFieldList;
    } catch (error) {
      console.error("获取项目概览失败:", error);
      ElMessage.error("获取项目信息失败");
    }
  };

  const getProjectList = async (): Promise<void> => {
    try {
      const res: ProjectTypeListResponse = await getProjectTypeList({
        page: 1,
        size: 1000,
      });

      projectList.value = (res.result?.map((item: ProjectTypeItem) => ({
        label: item.name?.zh_CN as string,
        value: item.id as string,
      })) || []) as IOptions[];
    } catch (error) {
      console.error("获取项目类型列表失败:", error);
      ElMessage.error("获取项目类型失败");
    }
  };

  const save = async (): Promise<void> => {
    try {
      const params: EditBaseInfoParams = {
        id: route.query.projectId as string,
        name: {
          zh_CN: formData.name,
        },
        code: formData.code,
        projectTypeId: formData.projectTypeId,
        plannedStartTime: formatDate(formData.plannedDate[0], "datetime"),
        plannedEndTime: formatDate(formData.plannedDate[1], "datetime"),
        plannedDurationDay: formData.plannedDurationDay,
        actualStartTime: formatDate(formData.actualDate[0], "datetime"),
        actualEndTime: formatDate(formData.actualDate[1], "datetime"),
        actualDurationDay: formData.actualDurationDay,
        remark: formData.remark,
        cover: formData.cover,
        customFieldList: getCustomFormSchema.value,
      };

      const result = await editBaseInfoAJAX(params);
      if (result.code === 200) {
        ElMessage.success("保存成功");
      } else {
        ElMessage.error("保存失败");
      }
    } catch (error) {
      console.error("保存失败:", error);
      ElMessage.error("保存失败");
    }
  };

  // 处理文件选择
  const handleAvatarSuccess: UploadProps["onChange"] = (
    uploadFile: UploadFile,
  ) => {
    console.log("uploadFile", uploadFile);

    // 清除之前的文件列表
    uploadRef.value?.clearFiles();

    // 检查文件是否存在且是图片
    if (!uploadFile.raw || !uploadFile.raw.type.startsWith("image/")) {
      ElMessage.error("请选择有效的图片文件");
      return;
    }

    const file = uploadFile.raw;

    // 创建FileReader来读取base64
    const reader = new FileReader();

    reader.onload = (e: ProgressEvent<FileReader>) => {
      if (e.target?.result) {
        // 将base64数据保存到formData
        formData.cover = e.target.result as string;
        console.log("封面已保存为base64");
        ElMessage.success("封面图片上传成功");
      }
    };

    reader.onerror = () => {
      ElMessage.error("文件读取失败!");
    };

    // 读取文件为base64
    reader.readAsDataURL(file);
  };

  // 定义基础字段

  const getBaseFormSchema = (): FormSchemaItem[] => [
    {
      component: "input",
      prop: "name",
      label: "项目名称",
      rules: [{ required: true, message: "请输入项目名称", trigger: "change" }],
    },
    {
      component: "input",
      prop: "code",
      label: "项目编码",
      showWordLimit: true,
      maxlength: "50",
      rules: [{ required: true, message: "请输入项目编码", trigger: "change" }],
    },
    {
      component: "select",
      prop: "projectTypeId",
      label: "项目类型",
      showWordLimit: true,
      maxlength: "10",
      options: projectList.value,
      rules: [{ required: true, message: "请选择项目类型", trigger: "change" }],
    },
    {
      component: "date-picker",
      type: "datetimerange",
      label: "计划日期",
      prop: "plannedDate",
      startPlaceholder: "开始日期",
      endPlaceholder: "结束日期",
    },
    {
      component: "input",
      type: "inputSelect",
      prop: "plannedDurationDay",
      unit: "plannedDurationDayUnit",
      label: "项目工期",
    },
    {
      component: "date-picker",
      type: "datetimerange",
      label: "实际日期",
      prop: "actualDate",
      startPlaceholder: "开始日期",
      endPlaceholder: "结束日期",
    },
    {
      component: "input",
      type: "inputSelect",
      prop: "actualDurationDay",
      unit: "actualDurationDayUnit",
      label: "实际工期",
    },
    {
      component: "input",
      type: "textarea",
      label: "项目描述",
      prop: "remark",
      showWordLimit: true,
      maxlength: "100",
    },
  ];
  const getCustomFormSchema = computed((): any => {
    const field: FormSchemaItem = addField.value;
    addField.value = null;
    if (field) {
      personalCustomFields.value.push(field);
    }
    return [...projectTemplateFields.value, ...personalCustomFields.value];
  });
  const baseFields = ref<FormSchemaItem[]>(getBaseFormSchema());
  const projectTemplateFields = ref<any>([]);
  const personalCustomFields = ref<any>([]);

  // 动态添加字段
  const addField = ref<FormSchemaItem | null>(null);
  const handleCreateOrEdit = (formData: any) => {
    isShowAddFieldDialog.value = false;
    console.log("handleCreateOrEdit", formData);
    const type = formData.typex.toLowerCase();
    const data: FormSchemaItem = {
      component: type,
      type: type,
      label: formData.displayName,
      prop: type,
      rules: [
        {
          required: formData.required,
          message: "请选择项目类型",
          trigger: "change",
        },
      ],
    };
    console.log("handleCreateOrEdit", formData, data);
    if (data) addField.value = data;
  };

  // 使用函数封装 formSchema
  const formSchema = computed((): FormSchemaItem[] => {
    return baseFields.value;
  });

  // 生命周期

  // 获取项目全局基础字段
  const projectGlobalBaseFields = async () => {
    const res = await getDetailByTargetType("PROJECT_BASE_FIELD");
    console.log(JSON.parse(res.config), "projectGlobalBaseFields");
    const baseFields = JSON.parse(res.config);
    baseFields.forEach((item) => {
      console.log(
        "getFieldType()",
        getFieldType(item.uiType),
        item.uiType,
        item.displayName,
      );
    });
  };
  onMounted(() => {
    projectGlobalBaseFields();
    getProjectOverview();
    getProjectList();
  });
</script>

<style>
  .field-sort-popover {
    border-radius: 4px;
    padding: 8px !important;
    box-shadow: 0px 8px 10px -5px #00000014;
  }
  .cover-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .cover-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    text-align: center;
  }
</style>
<style scoped lang="scss">
  .cover_image {
    width: 128px;
    height: 128px;
    object-fit: cover;
  }
  .base-info-container {
    padding: 16px;

    .form-title {
      font-weight: 500;
      font-size: 18px;
      line-height: 22px;
      .field-setting {
        display: flex;
        align-items: center;
        gap: 4px;
        cursor: pointer;
        img {
          width: 16px;
          height: 16px;
        }
        span {
          font-family: PingFang SC;
          font-weight: 400;
          font-style: Regular;
          font-size: 14px;
          leading-trim: NONE;
          line-height: 20px;
          letter-spacing: 0%;
        }
      }
    }
    .form-content {
      display: flex;
      .cover-container {
        padding: 12px;
        margin: 12px;
        display: flex;
        flex-direction: column;
        gap: 12px;
        border-left: 1px solid #ebeef5;
        height: 200px;
      }
    }
    .bottom {
      width: 600px;
    }
    .form-container {
      width: 600px;
      margin-top: 16px;
    }
    .save-btn {
      margin-left: 200px;
      width: 120px;
    }
  }
</style>
